/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Modulo3;

import Modelo.DAL.ConexionBD;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONObject;
import Acceso.Security;

/**
 *
 * @author glpc
 */
public class getRiesgo extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";
    private static final String[] ALLOWED = {"Administrador","Gestionar Riesgos"};
    
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {
        if (!Security.validateSession(request, ALLOWED)) {
            Security.privilegeError(response);
            return mapping.findForward("errorPriv");
        }

        String nombreAux = request.getParameter("nombreAux");
        response.setContentType("text/json");
        JSONObject data = new JSONObject();
        data.put("obtRiesgo", obtenerRiesgo(nombreAux));
        System.out.println("data: "+data.toString());
        PrintWriter pw = response.getWriter();
        pw.write(data.toString());
        pw.flush();
        pw.close();

        return mapping.findForward(FAILURE);
    }

    public JSONObject obtenerRiesgo(String nombreAux) {
        ConexionBD conex = new ConexionBD();
        JSONObject Rie = new JSONObject();
        Statement st;
        ResultSet rs;
        try {
            st = conex.session.createStatement();

            String query = "SELECT nombre FROM  riesgo where nombre = '" + nombreAux+"';";
            System.out.println("Seelect: "+query);
            rs = st.executeQuery(query);
            int i = 0;
            while (rs.next()) {
                JSONObject nombre = new JSONObject();
                nombre.put("nombre", rs.getString(1));
                Rie.put(""+i++, nombre);
            }

        } catch (Exception e) {
        }
        return Rie;
    }
}
